/*
 *
 * Copyright 2018 Asylo authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#ifndef ASYLO_PLATFORM_POSIX_IO_IO_CONTEXT_EVENTFD_H_
#define ASYLO_PLATFORM_POSIX_IO_IO_CONTEXT_EVENTFD_H_

#include <sys/eventfd.h>

#include <thread>

#include "absl/synchronization/mutex.h"
#include "asylo/platform/posix/io/io_manager.h"

namespace asylo {
namespace io {
// IOContext implementation wrapping an epoll file descriptor
class IOContextEventFd : public IOManager::IOContext {
 public:
  explicit IOContextEventFd(unsigned int initval, int flags)
      : counter_(initval) {
    if (flags & EFD_SEMAPHORE) {
      semaphore_ = true;
    } else {
      semaphore_ = false;
    }
    if (flags & EFD_NONBLOCK) {
      nonblock_ = true;
    } else {
      nonblock_ = false;
    }
  }

  ssize_t Read(void *buf, size_t count) override;
  ssize_t Write(const void *buf, size_t count) override;
  int Close() override;

 private:
  // Host file descriptor implementing this stream.
  uint64_t counter_;
  bool semaphore_;
  bool nonblock_;
  absl::Mutex counter_mutex_;
};

}  // namespace io
}  // namespace asylo

#endif  // ASYLO_PLATFORM_POSIX_IO_IO_CONTEXT_EVENTFD_H_
